import router, { resetRouter } from "@/router";
import { Message } from "element-ui";
import { getDictPage } from "@/api/system/dict";
import { setToken, removeToken } from "@/utils/auth"; // get token from cookie
import { authLogin, logout } from "@/api/auth";
import { queryUserList } from "@/api/user";
const getDefaultState = () => {
  return {
    id: sessionStorage.getItem("userid") ? sessionStorage.getItem("userid") : 0, // userid
    account: "", // nickname
    name: "", // nickname
    email: "", // nickname
    role: "0", // role
    permission: [], //用户角色信息
    dictsMap: {},
    dictsData: [],
    phone: "",
  };
};

const state = getDefaultState();

const mutations = {
  SET_ID: (state, id) => {
    state.id = id;
    sessionStorage.setItem("userid", id);
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account;
  },
  SET_NAME: (state, options) => {
    const { userName, phone } = options;
    state.name = userName;
    state.phone = phone;
    localStorage.setItem("userName", userName);
  },
  SET_EMAIL: (state, email) => {
    state.email = email;
  },
  SET_ROLE: (state, role) => {
    state.role = role;
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission;
  },
};

const actions = {
  // 用户登录
  login({ commit, dispatch }, userInfo) {
    return new Promise((resolve, reject) => {
      authLogin(userInfo)
        .then((response) => {
          if (response.result == 0) {
            const { user, token } = response.data;
            const { id, username, phone, roleSmallVO } = user;
            setToken(token);
            commit("SET_ID", id);
            // commit("SET_ACCOUNT", userAccount);
            commit("SET_NAME", {
              userName: username,
              phone,
            });
            dispatch(
              "permission/generateRoutes",
              {
                role: roleSmallVO.id,
                permission: "",
              },
              { root: true }
            );
            resolve();
            // commit("SET_EMAIL", email);
            // commit("SET_ROLE", role);
            // commit(
            //   "SET_PERMISSION",
            //   userPermission === "" ? [] : JSON.parse(userPermission)
            // );
            // dispatch(
            //   "permission/generateRoutes",
            //   {
            //     role,
            //     permission: userPermission,
            //   },
            //   { root: true }
            // ).then((accessRoutes) => {
            //   router.addRoutes(accessRoutes);

            //   dispatch("getAllDictData")
            //     .then((res) => {
            //       resolve();
            //     })
            //     .catch((err) => {
            //       resolve();
            //     });
            //   resolve();
            // });
          } else {
            Message({
              message: response.data.message,
              type: "error",
              duration: 5 * 1000,
            });
            reject();
          }
        })
        .catch((error) => {
          // Message({
          //   message: "登录异常，" + error,
          //   type: "error",
          //   duration: 5 * 1000,
          // });
          reject(error);
        });
    });
  },

  // 获取用户信息
  getInfo({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      queryUserList(state.name)
        .then((response) => {
          const { rows } = response.data;
          if (Array.isArray(rows) && rows.length) {
            const { id, userAccount, nickName, email, role, permission } =
              rows[0];
            commit("SET_ID", id);
            commit("SET_ACCOUNT", userAccount);
            commit("SET_NAME", nickName);
            commit("SET_EMAIL", email);
            commit("SET_ROLE", role);
            commit(
              "SET_PERMISSION",
              permission === "" ? [] : JSON.parse(permission)
            );
            dispatch("getAllDictData")
              .then((res) => {
                resolve(rows[0]);
              })
              .catch((err) => {
                resolve(rows[0]);
              });
          } else {
            reject(rows);
          }
        })
        .catch((error) => {
          commit("SET_ID", 0);
          reject(error);
        });
    });
  },

  // 用户登出
  logout({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then((response) => {
          if (response.result == 0) {
            commit("SET_ID", 0);
            state.dictsMap = {};
            state.dictsData = [];
            removeToken();
            resetRouter();
            dispatch("tagsView/delAllViews", null, { root: true });
            resolve();
          } else {
            Message({
              message: response.msg,
              type: "error",
              duration: 5 * 1000,
            });
            reject();
          }
        })
        .catch((error) => {
          Message({
            message: "登录异常，" + error,
            type: "error",
            duration: 5 * 1000,
          });
          reject(error);
        });
    });
  },

  getAllDictData({ commit, dispatch, state }) {
    return new Promise(async (resolve, reject) => {
      try {
        const par = { limit: 10000, offset: 1 };
        const res = await getDictPage(par);
        const dictsMap = state.dictsMap;
        const dictDataMap = {};
        const { data } = res;
        const { rows } = data;
        if (Array.isArray(rows) && rows.length) {
          rows.map((item) => {
            const { dictType, showFlag, dictValue } = item;
            if (!dictsMap[dictType]) dictsMap[dictType] = [];
            const flag = !dictsMap[dictType].some(
              (el) => el.dictValue === dictValue
            );
            if (showFlag == 1 && flag) state.dictsMap[dictType].push(item);
            if (!dictDataMap[dictType]) {
              dictDataMap[dictType] = item;
            }
          });
          try {
            state.dictsData = Object.keys(dictDataMap).map((key) => {
              return dictDataMap[key];
            });
          } catch (error) {
            console.log(error);
          }
        }
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
